// 登陆管理后台
// const config = require('./config')
const cheerio = require('cheerio')
const puppeteer = require('puppeteer');
const notifier = require('node-notifier');
const path = require('path')
const childe_process = require('child_process')

function autoLogin() {
    return new Promise(async (resolve, reject) => {
        const browser = await puppeteer.launch({
            headless: true,
            // 视口大小
            defaultViewport: {
                width: 1920,
                height: 1080
            },
            // 调节窗口大小
            args: [
                '--window-size=1920,1080'
            ]
        })
        const page = await browser.newPage()

        await page.goto(`https://live.douyin.com/185351619263`)

        await page.waitForTimeout(2000)

        console.log('开始检测聊天列表')

        // await clickByText(page, 'button', '直播中')
        const chatRoom = await page.$('.webcast-chatroom')
        if (chatRoom) {
            console.log('检查到了聊天列表')
        } else {
            console.log('没哟检查到了聊天列表')
        }
        let currentChatLen = 0
        let chatList = []
        let notifyIndex = 0
        let isNotifyEnd = true
        // 抓取评论列表
        setInterval(async () => {
            const divs = await page.$$eval('.webcast-chatroom___items > div:nth-child(1) .webcast-chatroom___item', el => el.map(el => el.innerHTML))
            if (divs.length > currentChatLen) {
                for (let i = 0; i < divs.length; i++) {
                    if (!currentChatLen || i > currentChatLen) {
                        // 解析DOM
                        const $ = cheerio.load(divs[i])
                        const chatUserName = $('span:nth-child(2)').text()
                        const chatContent = $('span.webcast-chatroom___content-with-emoji-text').text()
                        if (chatContent) chatList.push({name: chatUserName, content: chatContent})
                    }
                }
                currentChatLen = divs.length - 1
            }
        }, 500)

        // 播报评论
        setInterval(() => {
            if (chatList.length && notifyIndex < currentChatLen && isNotifyEnd) {
                isNotifyEnd = false
                notifier.notify({
                    'title': chatList[notifyIndex].name,
                    'message': chatList[notifyIndex].content,
                    icon: path.join(__dirname, 'a.jpg'),
                });
                notifyIndex += 1
                setTimeout(() => { isNotifyEnd = true}, 2000)
            }
        }, 300)
        
        let interRoomList = []   // 进入房间列表
        let spiderIndex = 0      // 抓取到的index
        let readIndex = 0        // 播报到第几个
        let isReadEnd = true     // 是否朗读完毕
        // 抓取进入房间列表
        setInterval(async () => {
            const divs = await page.$$eval('.webcast-chatroom___items > div:nth-child(2) .webcast-chatroom___item', el => el.map(el => el.innerHTML))
            if (divs.length > spiderIndex) {
                for (let i = 0; i < divs.length; i++) {
                    if (!spiderIndex || i > spiderIndex) {
                        // 解析DOM
                        const $ = cheerio.load(divs[i])
                        const interUserName = $('span:nth-child(2)').text()
                        // 这里存在一个人名插入多次的情况
                        !interRoomList.includes(interUserName) && (interRoomList.push(interUserName))
                    }
                }
                spiderIndex = divs.length - 1
            }
        }, 500)
        
        // 定时朗读
        setInterval(() => {
            if (interRoomList.length && readIndex < interRoomList.length && isReadEnd) {
                isReadEnd = false
                childe_process.exec(`say 欢迎${interRoomList[readIndex]}`, function(err, stdout, stderr) {
                    readIndex += 1
                    isReadEnd = true
                })
            }
        }, 300)
    })
}

autoLogin()
